package com.sardine.base.threads;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 北京京东世纪贸易有限公司<br>
 * Created with IntelliJ IDEA.
 * Date:2017/1/18
 * Time:11:12
 * 有名字的线程工厂类，有名字，方面线程dump 时候，能知道是哪个有问题
 * @author daifeng<br>
 *         daifeng@jd.com
 * @since JDK 1.7 <br>
 * Copyright (c) 2017 JD System Incorporated All Rights Reserved.
 */
public class ThreadNamedFactory implements ThreadFactory {
    private static final Logger logger = LoggerFactory.getLogger(ThreadNamedFactory.class);

    /**
     * 系统全局线程池计数器
     */
    private static final AtomicInteger poolCount = new AtomicInteger();

    /**
     * 当前线程池计数器
     */
    final AtomicInteger threadCount = new AtomicInteger(1);
    final ThreadGroup group;
    final String namePrefix;
    final boolean isDaemon; //是否守护线程，true的话随主线程退出而退出，false的话则要主动退出

    /**
     * 构造函数，默认非守护线程
     *
     * @param prefix 前缀，后面会自动加上-T-
     */
    public ThreadNamedFactory(String prefix) {
        this(prefix, false);
    }

    /**
     * 构造函数
     *
     * @param prefix 前缀，后面会自动加上-T-
     * @param daemon 是否守护线程，true的话随主线程退出而退出，false的话则要主动退出
     */
    public ThreadNamedFactory(String prefix, boolean daemon) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        namePrefix = prefix + "-" + poolCount.getAndIncrement() + "-T-";
        isDaemon = daemon;
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r, namePrefix + threadCount.getAndIncrement(), 0);
        t.setDaemon(isDaemon);
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}